//
//  Util.m
//  EncryptionTPB
//
//  Created by LvJianfeng on 15/9/15.
//  Copyright © 2015年 coderjianfeng. All rights reserved.
//

#import "JFUtil.h"

@implementation JFUtil
/**
 *  隐藏空白cell得横线
 *
 *  @param tableView 操作表
 */
+ (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *emtryView =[ [UIView alloc]init];
    emtryView.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:emtryView];
    [tableView setTableHeaderView:emtryView];
}
/**
 *  弹出提醒Label
 *
 *  @param view  所属视图
 *  @param text  提示文本
 *  @param delay 倒计时移除
 */
+ (void)showMBAlertLabel:(UIView*)view text:(NSString*)text afterDelay:(NSTimeInterval)delay{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = text;
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:delay];
}
/**
 *  设置textfield提醒文本颜色
 *
 *  @param textField 设置对象
 *  @param phcolor   设置颜色
 */
+ (void)setTextFieldPlacehoderColor:(UITextField*)textField placeHoderColor:(UIColor*)phcolor{
    [textField setValue:phcolor forKeyPath:@"_placeholderLabel.textColor"];
}
/**
 *  设置Textfield文本
 *
 *  @param textField      设置对象
 *  @param textFieldColor 文本颜色
 *  @param placehoderStr  提醒文本
 */
+ (void)setTextFieldCustom:(UITextField*)textField textColor:(UIColor*)textFieldColor placehoder:(NSString*)placehoderStr{
    textField.backgroundColor = [UIColor whiteColor];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.textColor = textFieldColor;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.returnKeyType = UIReturnKeySearch;
    textField.placeholder = placehoderStr;
    [textField setValue:[UIColor customLightPlaceColor] forKeyPath:@"_placeholderLabel.textColor"];
}
/**
 *  设置导航条样式
 *
 *  @param navigationController 设置对象
 *  @param titleColor           标题颜色
 *  @param titlefont            标题字体
 */
+ (void)setNavigationTitleStyle:(UINavigationController *)navigationController titleColor:(UIColor*)titleColor titleFont:(UIFont*)titleFont{
    [navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:titleColor, NSForegroundColorAttributeName,titleFont,NSFontAttributeName, nil]];
}
/**
 *  设置导航条样式 (弃用)
 *
 *  @param navigationController 设置对象
 *  @param value                系统透明设置
 *  @param tintColor            tintColor
 *  @param titleColor           标题颜色
 *  @param titlefont            标题字体
 */
+ (void)setNavigationControllerStyle:(UINavigationController *)navigationController translucent:(BOOL)value tintColor:(UIColor*)tintColor titleColor:(UIColor*)titleColor titleFont:(UIFont*)titlefont
{
    //[navigationController.navigationBar setCustomBackgroundColor:[UIColor customSystemColor]];
    //value==no 去除系统透明
    [navigationController.navigationBar setTranslucent:value];
    navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:titleColor, NSForegroundColorAttributeName,titlefont,NSFontAttributeName, nil]];
}
/**
 *  设置全局导航统一样式
 *
 *  @param barTintColor    bar颜色
 *  @param backgroundColor 背景色
 *  @param translucent     是否透明
 *  @param ishidden        是否隐藏返回文本
 */
+ (void)setNavigationAppearance:(UIColor*)barTintColor tintColor:(UIColor*)tintColor backgroundColor:(UIColor*)backgroundColor{
    //在info.plist中添加一个字段：view controller -base status bar 设置为NO；
    //导航颜色
    [[UINavigationBar appearance] setBarTintColor:barTintColor];
    [[UINavigationBar appearance] setBackgroundColor:backgroundColor];
//    //默认带有一定透明效果，可以使用以下方法去除系统效果
//    [[UINavigationBar appearance] setTranslucent:translucent];
    [[UINavigationBar appearance] setTintColor:tintColor];
}
/**
 *  设置全局navigation返回文本显示
 *
 *  @param ishidden 是否隐藏
 */
+ (void)hideBackTitle:(BOOL)ishidden{
    if (ishidden) {
        //隐藏返回文本
        [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                             forBarMetrics:UIBarMetricsDefault];
    }
}
/**
 *  设置全局navigation返回图片
 *
 *  @param image 返回图片
 */
+ (void)setNavigationAppearanceBackImage:(UIImage *)image{
    UIImage *backButtonImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 0, 0)];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}
/**
 *  设置navigation得下面横线
 *
 *  @param lineColor 颜色
 */
+ (void)setNavigationAppearanceShadowColorImage:(UIColor *)lineColor{
    [[UINavigationBar appearance] setShadowImage:[self imageWithColor:[UIColor whiteColor] size:CGSizeMake(320, 1)]];
}

/**
 *  颜色转image
 *
 *  @param color 颜色
 *  @param size  大小
 *
 *  @return image
 */
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
#pragma mark 验证
/**
 *  验证是否为数字号码
 *
 *  @param number 验证对象
 *
 *  @return 返回bool
 */
+ (BOOL)validateNumber:(NSString*)number {
    BOOL rs = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            rs = NO;
            break;
        }
        i++;
    }
    return rs;
}
/**
 *  验证是否为邮箱
 *
 *  @param number 验证对象
 *
 *  @return 返回bool
 */
+ (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

#pragma mark 字符串操作
/**
 *  去除字符串首尾的空格
 *
 *  @param value 操作对象
 *
 *  @return 字符串对象
 */
+ (NSString *)removeLeadingAndTrailingSpaces:(NSString *)value{
    if (isNullString(value)) {
        NSLog(@"%s:%d %s:字符串为空",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],__LINE__,__FUNCTION__);
        return nil;
    }
    return [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
/**
 *  去除字符串所有空格
 *
 *  @param value 操作对象
 *
 *  @return 字符串对象
 */
+ (NSString *)replaceBlankSpace:(NSString *)value{
    [self checkStringValue:value];
    return [value stringByReplacingOccurrencesOfString:@" " withString:@""];
}
/**
 *  替换号码得部分字符：@"-",@"+86",@"+1",@"＋",@"(",@")", @" ",@" ",@""
 *
 *  @param value 操作对象
 *
 *  @return 字符串对象
 */
+ (NSString *)replacePhoneNumber:(NSString *)value{
    [self checkStringValue:value];
    NSArray *strReplace = [NSArray arrayWithObjects:@"-",@"+86",@"+1",@"＋",@"(",@")", @" ",@" ",@"",nil];//@" "
    for (int i=0; i<strReplace.count;i++) {
        value = [value stringByReplacingOccurrencesOfString:strReplace[i] withString:@""];
    }
    return value;
}
/**
 *  替换字符串
 *
 *  @param value   操作对象
 *  @param reValue 需要替换得字符
 *  @param withStr 替换字符
 *
 *  @return 字符串对象
 */
+ (NSString *)replaceString:(NSString *)value replaceArray:(NSArray *)reValue replaceValue:(NSString *)withStr{
    [self checkStringValue:value];
    for (int i=0; i<reValue.count;i++) {
        value = [value stringByReplacingOccurrencesOfString:reValue[i] withString:withStr];
    }
    return value;
}
#pragma mark 字符串计算size
/**
 *  计算字符串得size
 *
 *  @param value   字符串值
 *  @param font    字体
 *  @param maxSize 最大size
 *
 *  @return 字符串size
 */
+ (CGSize)sizeWithString:(NSString *)value font:(UIFont *)font maxSize:(CGSize)maxSize{
    NSDictionary *dict = @{NSFontAttributeName : font};
    if (isNullString(value)) {
        return CGSizeMake(10, 10);
    }
    CGSize size =  [value boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}
#pragma mark 检查空字符串
+ (void)checkStringValue:(NSString*)value{
    if (isNullString(value)) {
        NSLog(@"%s:%d %s:字符串为空",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],__LINE__,__FUNCTION__);
        return;
    }
}
#pragma mark 时间格式化
/**
 *  格式化日期
 *
 *  @param date 日期
 *  @param type 格式化返回格式
 *
 *  @return 字符串
 */
+ (NSString *)dateFormatToString:(NSDate *)date formatType:(DateFormatType)type{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:[self dateFormatToStringInType:type]];
    NSString *formatDate = [dateFormatter stringFromDate:date];
    return formatDate;
}
/**
 *  格式化时间
 *
 *  @param timeStamp 秒
 *  @param type      格式化返回格式
 *
 *  @return 字符串
 */
+ (NSString *)dateFormatToStringFromTimeStamp:(NSInteger)timeStamp formatType:(DateFormatType)type
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:[self dateFormatToStringInType:type]];
    NSString *formatDate = [dateFormatter stringFromDate:date];
    return formatDate;
}


#pragma mark 未使用
- (NSString *)loadPlistFile:(NSString *)fileNameWithoutExtension
{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *plistPath = [pathArray objectAtIndex:0];
    NSString *filename=[plistPath stringByAppendingPathComponent:[fileNameWithoutExtension stringByAppendingString:@".plist"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filename]){
        return filename;
    }
    return nil;
}

#pragma mark 头文件没显示
+ (NSString *)dateFormatToStringInType:(DateFormatType)type{
    switch (type) {
        case Year:
            return @"yyyy";
            break;
        case YearMonth:
            return @"yyyyMM";
            break;
        case YearMonthHorizontalLine:
            return @"yyyy-MM";
            break;
        case YearMonthSlash:
            return @"yyyy/MM";
            break;
        case YearMonthPoint:
            return @"yyyy.MM";
            break;
        case YearMonthDay:
            return @"yyyyMMdd";
            break;
        case YearMonthDayHorizontalLine:
            return @"yyyy-MM-dd";
            break;
        case YearMonthDaySlash:
            return @"yyyy/MM/dd";
            break;
        case YearMonthDayPoint:
            return @"yyyy.MM.dd";
            break;
            
        case Month:
            return @"MM";
            break;
        case MonthDay:
            return @"MMdd";
            break;
        case MonthDayHorizontalLine:
            return @"MM-dd";
            break;
        case MonthDayPoint:
            return @"MM.dd";
            break;
        case MonthDaySlash:
            return @"MM/dd";
            break;
        case MonthDayYear:
            return @"MMddyyyy";
            break;
        case MonthDayYearHorizontalLine:
            return @"MM-dd-yyyy";
            break;
        case MonthDayYearPoint:
            return @"MM.dd.yyyy";
            break;
        case MonthDayYearSlash:
            return @"MM/dd/yyyy";
            break;
        case MonthYear:
            return @"MMyyyy";
            break;
        case MonthYearHorizontalLine:
            return @"MM-yyyy";
            break;
        case MonthYearPoint:
            return @"MM.yyyy";
            break;
        case MonthYearSlash:
            return @"MM/yyyy";
            break;
            
        case Day:
            return @"dd";
            break;
        case DayMonth:
            return @"ddMM";
            break;
        case DayMonthHorizontalLine:
            return @"dd-MM";
            break;
        case DayMonthPoint:
            return @"dd.MM";
            break;
        case DayMonthSlash:
            return @"dd/MM";
            break;
        case DayMonthYear:
            return @"ddMMyyyy";
            break;
        case DayMonthYearHorizontalLine:
            return @"dd-MM-yyyy";
            break;
        case DayMonthYearPoint:
            return @"dd.MM.yyyy";
            break;
        case DayMonthYearSlash:
            return @"dd/MM/yyyy";
            break;
        default:
            break;
    }
    return @"yyyyddMM";
}
@end

#pragma mark 自定义颜色
/**
 *  自定义全局使用颜色
 */
@implementation UIColor (CustomColor)

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+ (UIColor *) colorAlphaWithHexString: (NSString *) stringToConvert alpha:(CGFloat)alpha
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}

#pragma mark customColor

+ (UIColor *)customGrayColor
{
    return [self colorWithRed:84 green:84 blue:84];
}

+ (UIColor *)customRedColor
{
    return [self colorWithRed:231 green:76 blue:60];
}

+ (UIColor *)customYellowColor
{
    return [self colorWithRed:241 green:196 blue:15];
}

+ (UIColor *)customGreenColor
{
    //return [self colorWithRed:46 green:204 blue:113];
    return [UIColor colorWithHexString:@"#88c057"];
}

+ (UIColor *)customBlueColor
{
    return [self colorWithRed:52 green:152 blue:219];
}

//
+ (UIColor *)customSystemColor
{
    return [UIColor colorWithHexString:@"#48a0dc"];
}

+ (UIColor *)customDarkPlaceColor
{
    return [UIColor colorWithHexString:@"#546A79"];
}
+ (UIColor *)customLightPlaceColor
{
    return [UIColor colorWithHexString:@"#98a6af"];
}
+ (UIColor *)customControllerBackgroundColor
{
    return [UIColor colorWithHexString:@"#eeeeee"];
}
+ (UIColor *)customControllerBackgroundColorAlpha
{
    return [UIColor colorAlphaWithHexString:@"#eeeeee" alpha:0.8];
}
#pragma mark - Private class methods

+ (UIColor *)colorWithRed:(NSUInteger)red
                    green:(NSUInteger)green
                     blue:(NSUInteger)blue
{
    return [UIColor colorWithRed:(float)(red/255.f)
                           green:(float)(green/255.f)
                            blue:(float)(blue/255.f)
                           alpha:1.f];
}

@end

